<template>
  <div>
    <!-- form
                inline,他的属性值为true,代表行内form,一行可以放置多个表单
            el-option
            label 下拉菜单展示文字
            value 将来是select要收集数据
       -->
    <el-form :inline="true" class="demo-form-inline" :model="cForm">
      <el-form-item label="一级分类">
        <el-select
          placeholder="请选择"
          v-model="cForm.category1Id"
          @change="getC2List"
        >
          <el-option
            :label="c1.name"
            :value="c1.id"
            v-for="c1 in c1List"
            :key="c1.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!--  -->
      <el-form-item label="二级分类">
        <el-select
          placeholder="请选择"
          v-model="cForm.category2Id"
          @change="getC3List"
        >
          <el-option
            :label="c2.name"
            :value="c2.id"
            v-for="c2 in c2List"
            :key="c2.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <!--  -->
      <el-form-item label="三级分类">
        <el-select
          placeholder="请选择"
          v-model="cForm.category3Id"
          @change="handler"
        >
          <el-option
            :label="c3.name"
            :value="c3.id"
            v-for="c3 in c3List"
            :key="c3.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "Category",
  data() {
    return {
      // 收集数据
      cForm: {
        category1Id: "",
        category2Id: "",
        category3Id: "",
      },
      // 存储一级分类的数据
      c1List: [],
      // 存储二级分类的数据
      c2List: [],
      // 存储三级分类的数据
      c3List: [],
    };
  },
  mounted() {
    //   获取一级分类的请求函数
    this.getC1List();
  },
  methods: {
    async getC1List() {
      let result = await this.$ajax.attr.reqGetCategory1();
      if (result.code == 200) {
        this.c1List = result.data;
      }
    },
    async getC2List() {
      this.c2List = [];
      this.c3List = [];
      this.cForm.category2Id = "";
      this.cForm.category3Id = "";
      let { category1Id } = this.cForm;
      this.$emit('getCategoryId',{id:category1Id,flag:1});
      let result = await this.$ajax.attr.reqGetCategory2(category1Id);
      if (result.code == 200) {
        this.c2List = result.data;
      }
    },
    async getC3List() {
      this.c3List = [];
      this.cForm.category3Id = "";
      let { category2Id } = this.cForm;
      this.$emit('getCategoryId',{id:category2Id,flag:2});
      let result = await this.$ajax.attr.reqGetCategory3(category2Id);
      if (result.code == 200) {
        this.c3List = result.data;
      }
    },
    // 三级分类的chang事件
    handler() {
      const { category3Id } = this.cForm;
      this.$emit('getCategoryId',{id:category3Id,flag:3});
    },
  },
};
</script>

<style>
</style>